package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.MyEnum.NumberConstant;
import com.example.entity.UserAddress;
import com.example.mapper.UserAddressMapper;
import com.example.service.UserAddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/address")
public class UserAddressController {
    @Resource
    private UserAddressService userAddressService;
    @Autowired
    private UserAddressMapper userAddressMapper;

    /**
     * 根据id 删除用户地址
     *
     * @param id
     * @param openid
     * @return
     */
    @Transactional
    @GetMapping("delete")
    public Boolean delete(Long id, String openid) {
        Objects.requireNonNull(id, "id is null");
        Objects.requireNonNull(openid, "openid is null");
        List<UserAddress> UserAddressList = this.list(openid);
        // 如果用户的地址只有一个那就直接删除
        if (UserAddressList.size() == NumberConstant.ONE) {
            boolean success = userAddressService.removeById(id);
            if (!success) {
                throw new RuntimeException("Failed to delete user address with id " + id);
            }
            return false;
        }
        // 创建optional集合 过滤掉传来的地址id
        // 挨个循环如果里面状态没有为NumberConstant.ONE 的那就设置其中一个为默认
        Optional<UserAddress> firstUserAddress = UserAddressList.stream()
                .filter(os -> !os.getId().equals(id))
                .findFirst();
        // 集合不为空并且地址状态不为NumberConstant.ONE
        if (firstUserAddress.isPresent() && !firstUserAddress.get().getState().equals(NumberConstant.ONE)) {
            firstUserAddress.get().setState(NumberConstant.ONE);
            userAddressService.updateById(firstUserAddress.get());
        }
        boolean success = userAddressService.removeById(id);
        if (!success) {
            throw new RuntimeException("Failed to delete user address with id " + id);
        }
        return success;
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("get")
    public UserAddress getUserAddress(Long id) {
        Objects.requireNonNull(id, "address id is null");
        return userAddressMapper.selectById(id);
    }


    /**
     * 该代码正在添加一个用户地址，如果没有现有地址，
     * 或者如果存在现有地址但没有一个设置为默认地址，则将其设置为默认地址。
     * 如果将新地址设置为默认地址，则代码会将所有其他地址更新为非默认地址。
     * 一种可能的优化是使用单个数据库查询将所有其他地址更新为非默认地址，
     * 而不是单独更新每个地址。这可以通过删除检查并在
     * .list.stream().noneMatch(o -> o.getState() == NumberConstant.ONE)userAddress.getState() == NumberConstant.ONE
     * 这将减少数据库访问次数并提高性能。
     *
     * @param userAddress
     * @return Boolean
     */
    @Transactional
    @PostMapping("/add")
    public Boolean add(@RequestBody UserAddress userAddress) {
        Objects.requireNonNull(userAddress, "UserAddress object is null");
        List<UserAddress> list = this.list(userAddress.getOpenid());
        /**
         * 没有数据直接添加并且为默认
         */
        boolean hasDefaultAddress = list.stream().noneMatch(o -> o.getState().equals(NumberConstant.ZERO));
        if (list.size() == NumberConstant.ZERO || hasDefaultAddress) {
            userAddress.setState(NumberConstant.ONE);
            return userAddressService.save(userAddress);
        }
        /**
         * 默认为NumberConstant.ONE  那就遍历所有数据  然后把所有的状态改为不默认
         */
        if (userAddress.getState().equals(NumberConstant.ONE)) {
            LambdaUpdateWrapper<UserAddress> userAddressLambdaQueryWrapper = new LambdaUpdateWrapper<>();
            userAddressLambdaQueryWrapper
                    .eq(UserAddress::getState, NumberConstant.ONE)
                    .set(UserAddress::getState, NumberConstant.ZERO);
            userAddressService.update(userAddressLambdaQueryWrapper);
        }
//            添加数据
        return userAddressService.save(userAddress);
    }


    /**
     * 修改默认地址和地址信息
     *
     * @param userAddress
     * @return Boolean
     */
    @PostMapping("/update")
    public Boolean update(@RequestBody UserAddress userAddress) {
        List<UserAddress> list = this.list(userAddress.getOpenid());
//        去数据库查 当前用户的所有地址
        if (userAddress.getState().equals(NumberConstant.ONE)) {
            boolean b = list.stream()
                    .anyMatch(o -> o.getState().equals(NumberConstant.ONE));
            if (b) {
                LambdaUpdateWrapper<UserAddress> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(UserAddress::getState, NumberConstant.ONE)
                        .eq(UserAddress::getOpenid, userAddress.getOpenid())
                        .set(UserAddress::getState, NumberConstant.ZERO);
                userAddressService.update(wrapper);
                userAddressService.updateById(userAddress);
            }
        }
//        如果当前地址状态为NumberConstant.ONE那就遍历所有地址的状态 如果也有NumberConstant.ONE 那就修改为NumberConstant.ZERO
        return userAddressService.updateById(userAddress);
    }

    /**
     * 获取用户地址
     *
     * @param openid
     * @return
     */
    @GetMapping("/getAddressList")
    public List<UserAddress> list(String openid) {
        log.info("获取用户{}地址", openid);
        return userAddressService.list(new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getOpenid, openid));
    }

}
